package com.lzp.java.concurrent.collection.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author lzp
 * @Description: 阻塞队列生产者消费者
 * @date 2021/3/2
 */
public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
        Thread producer = new Thread(new Producer(queue));
        Thread consumer = new Thread(new Consumer(queue));
        producer.start();
        consumer.start();
    }
}

class Producer implements Runnable {
    private BlockingQueue<Integer> queue;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("开始生产数据。。。");
        for (int i = 0; i < 10; i++) {
            try {
                queue.put(i);
                System.out.println("生产数据：" + i + ",队列数据：" + queue.toString());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            queue.put(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

class Consumer implements Runnable {
    private BlockingQueue<Integer> queue;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(1000);
            Integer val;
            while (!((val = queue.take()) == 10)) {
                System.out.println("消费数据：" + val + ",队列数据：" + queue.toString());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
